package com.yltrcc.blog.business.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HtmlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yltrcc.blog.business.ArticleService;
import com.yltrcc.blog.business.LogService;
import com.yltrcc.blog.generate.domain.*;
import com.yltrcc.blog.generate.mapper.custom.CategoryMapperCustom;
import com.yltrcc.blog.generate.mapper.custom.QuestionMapperCustom;
import com.yltrcc.blog.generate.mapper.custom.TagMapperCustom;
import com.yltrcc.blog.generate.mapper.generator.QuestionMapper;
import com.yltrcc.blog.model.model.ArchiveBo;
import com.yltrcc.blog.business.QuestionService;
import com.yltrcc.blog.model.model.BlogConst;
import com.yltrcc.blog.model.model.LogConstant;
import com.yltrcc.blog.model.exception.CheckException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Package: com.yltrcc.blog.service.impl
 * Date：2022-01-15
 * Time：15:37
 * Description：面试题库接口实现类
 *
 * @author yltrcc
 * @version 1.0
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Resource
    private QuestionMapperCustom questionMapperCustom;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private TagMapperCustom tagMapperCustom;

    @Resource
    private CategoryMapperCustom categoryMapperCustom;

    @Autowired
    protected LogService logService;

    @Autowired
    private ArticleService articleService;

    @Override
    public void save(Question question, Long[] tags, Long category, Long subCategory, HttpServletRequest request, Integer userId) throws Exception {
        if (StrUtil.isEmpty(question.getArticleTitle())) {
            throw  new CheckException("标题不能为空");
        }
        if (category != null) {
            question.setCategoryId(category);
        }
        if (subCategory != null) {
            question.setSubCategoryId(subCategory);
        }
        if (question.getId() == null) {
            // 判断文章链接是否重复
            if (!StrUtil.isEmpty(question.getArticleUrl())) {
                if (question.getArticleUrl().length() > 50) {
                    throw  new CheckException("路径不能大于50");
                }
                // 查询url是否重复
                int repeat = articleService.findRepeatByUrl(question.getArticleUrl());
                if (repeat != 0) {
                    throw  new CheckException("路径已存在");
                }
            }
            question.setUserId(userId);
            question.setArticleNewstime(DateUtil.date());
            question.setArticleUpdatetime(DateUtil.date());
            // 如果自定义链接为空则按时间戳生成链接
            if (StrUtil.isEmpty(question.getArticleUrl())) {
                question.setArticleUrl(String.valueOf(System.currentTimeMillis() / 1000));
            }
            // 如果没有选择略缩图则随机一张图
            if (StrUtil.isEmpty(question.getArticleThumbnail())) {
                question.setArticleThumbnail("/static/img/rand/" + RandomUtil.randomInt(1, 19) + ".jpg");
            }
            // 判断摘要是否为空
            if (StrUtil.isEmpty(question.getArticleSummary())) {
                // 如果摘要为空则取前五十字为摘要
                int post_summary = 50;
                if (StrUtil.isNotEmpty(BlogConst.OPTIONS.get("post_summary"))) {
                    post_summary = Integer.parseInt(BlogConst.OPTIONS.get("post_summary"));
                }
                // 清理html标签和空白字符
                String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(question.getArticleContentMd()));
                // 设置文章摘要
                if (summaryText.length() > post_summary) {
                    question.setArticleSummary(summaryText.substring(0, post_summary));
                } else {
                    question.setArticleSummary(summaryText);
                }
            }
            questionMapper.insert(question);
            // 添加日志
            logService.save(new Log(LogConstant.PUBLISH_AN_ARTICLE, LogConstant.SUCCESS,
                    ServletUtil.getClientIP(request), DateUtil.date()));
        } else {
            // 如果没有选择略缩图则随机一张图
            if (StrUtil.isEmpty(question.getArticleThumbnail())) {
                question.setArticleThumbnail("/static/img/rand/" + RandomUtil.randomInt(1, 19) + ".jpg");
            }
            // 判断摘要是否为空
            if (StrUtil.isEmpty(question.getArticleSummary())) {
                // 如果摘要为空则取前五十字为摘要
                int post_summary = 50;
                if (StrUtil.isNotEmpty(BlogConst.OPTIONS.get("post_summary"))) {
                    post_summary = Integer.parseInt(BlogConst.OPTIONS.get("post_summary"));
                }
                // 清理html标签和空白字符
                String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(question.getArticleContentMd()));
                // 设置文章摘要
                if (summaryText.length() > post_summary) {
                    question.setArticleSummary(summaryText.substring(0, post_summary));
                } else {
                    question.setArticleSummary(summaryText);
                }
            }
            // 文章最后修改时间
            question.setArticleUpdatetime(DateUtil.date());
            this.update(question, tags);
            // 添加日志
            logService.save(new Log(LogConstant.UPDATE_AN_ARTICLE, LogConstant.SUCCESS,
                    ServletUtil.getClientIP(request), DateUtil.date()));
        }


    }

    @Override
    public List<QuestionCustom> findAllQuestion(int status, String post) {
        return null;
    }

    @Override
    public PageInfo<QuestionCustom> findPageQuestion(int page, int limit, QuestionCustom questionCustom) {
        PageHelper.startPage(page, limit);
        List<QuestionCustom> lists = questionMapperCustom.findPageQuestion(questionCustom);
        return new PageInfo<>(lists);
    }

    @Override
    public Integer countByStatus(Integer status, String post) {
        return null;
    }


    @Override
    public Integer getCounts() {
        return questionMapperCustom.getCounts();
    }

    @Override
    public void remove(int id) throws Exception {

    }

    @Override
    public void recycle(int id, Integer integer) throws Exception {

    }


    @Override
    public QuestionCustom findByQuestionId(Integer questionId) {
        return questionMapperCustom.findByQuestionId(questionId);
    }

    @Override
    public void update(Question question, Long[] tags) throws Exception {
        // 修改文章
        questionMapper.updateByPrimaryKeySelective(question);
    }

    @Override
    public List<ArchiveBo> archives() {
        return null;
    }

    @Override
    public int findRepeatByUrl(String QuestionsUrl) {
        return 0;
    }

    @Override
    public QuestionCustom findByQuestionsUrl(String QuestionsUrl) {
        return questionMapperCustom.findByQuestionsUrl(QuestionsUrl);
    }
    @Override
    public List<Question> findByCategory(Long categoryId) {
        Question question = new Question();
        question.setCategoryId(categoryId);
        List<Question> lists = questionMapperCustom.findByCategory(question);
        if (lists == null) {
            return new ArrayList<>();
        }
        return lists;
    }

    @Override
    public PageInfo<QuestionCustom> findArtileByCategory(int page, int limit, Category category, int status) {
        return null;
    }

    @Override
    public PageInfo<QuestionCustom> findArtileByTag(Integer page, Integer limit, Tag tag, int status) {
        return null;
    }


    @Override
    public PageInfo<Question> findQuestionsByKeywords(String keywords, Integer page, Integer limit) {
        return null;
    }

    @Override
    public void updateQuestionsViews(Question Question) {

    }

    @Override
    public List<SubCategory> findSubCategoryByCategoryId(Integer categoryId) {
        List<SubCategory> lists = questionMapperCustom.findSubCategoryByCategoryId(categoryId);
        if (lists == null) {
            return new ArrayList<>();
        }
        return lists;
    }

    @Override
    public List<Category> findLowerCategoryByCategoryId(Integer categoryId) {
        List<Category> lists = questionMapperCustom.findLowerCategoryByCategoryId(categoryId);
        if (lists == null) {
            return new ArrayList<>();
        }
        return lists;
    }

    @Override
    public List<Question> findBySubCategory(Integer id) {
        List<Question> lists = questionMapperCustom.findBySubCategory(id);
        if (lists == null) {
            return new ArrayList<>();
        }
        return lists;
    }

    @Override
    public List<Category> findCategoryByTop() {
        List<Category> lists = questionMapperCustom.findCategoryByTop();
        if (lists == null) {
            return new ArrayList<>();
        }
        return lists;
    }

    @Override
    public Question selectByPrimaryKey(Integer id) {
        return questionMapper.selectByPrimaryKey(id);
    }


}
